<template>
  <div class="demo-container">
    <h2>Pinia 高级状态管理</h2>
    <p class="description">
      探索 Vue 3 中 Pinia 的高级特性，包括模块化状态管理、插件系统、持久化存储和高级组合式API集成。
    </p>

    <!-- 特性简介 -->
    <div class="feature-intro">
        <div class="feature-card">
          <h3>🏗️ 模块化状态</h3>
          <p>清晰的模块化结构，支持类型推断和自动代码提示</p>
        </div>
        <div class="feature-card">
          <h3>🔌 插件系统</h3>
          <p>强大的插件机制，支持状态持久化、调试和中间件</p>
        </div>
        <div class="feature-card">
          <h3>🔄 组合式风格</h3>
          <p>完全兼容组合式API，支持setup函数和响应式特性</p>
        </div>
      </div>

    <!-- 示例部分 -->
    <section class="example-section">
      <h3>1. 模块化 Store 演示</h3>
      
      <div class="demo-box">
        <div class="store-data">
          <h4>用户信息 (User Store)</h4>
          <div class="data-display">
            <p><strong>用户名:</strong> {{ userStore.user?.name || '未登录' }}</p>
            <p><strong>角色:</strong> {{ userStore.user?.role || '访客' }}</p>
            <p><strong>登录状态:</strong> {{ userStore.isLoggedIn ? '已登录' : '未登录' }}</p>
          </div>
          
          <div class="action-buttons">
            <button @click="login" class="btn" v-if="!userStore.isLoggedIn">
              登录
            </button>
            <button @click="logout" class="btn" v-else>
              登出
            </button>
          </div>
        </div>
        
        <div class="store-data">
          <h4>购物车 (Cart Store)</h4>
          <div class="data-display">
            <p><strong>商品数量:</strong> {{ cartStore.totalItems }}</p>
            <p><strong>总金额:</strong> ${{ cartStore.totalPrice ? cartStore.totalPrice.toFixed(2) : '0.00' }}</p>
          </div>
          
          <div class="cart-items">
            <div v-for="item in cartStore.items" :key="item.id" class="cart-item">
              <span>{{ item.name }}</span>
              <span>$${{ item.price ? item.price.toFixed(2) : '0.00' }}</span>
              <div class="quantity-control">
                <button @click="cartStore.decrementQuantity(item.id)" class="btn btn--secondary btn--small">-</button>
                <span>{{ item.quantity }}</span>
                <button @click="cartStore.incrementQuantity(item.id)" class="btn btn--secondary btn--small">+</button>
              </div>
            </div>
            <div v-if="cartStore.items.length === 0" class="empty-state">
              <div class="empty-state__text">购物车为空</div>
            </div>
          </div>
          
          <div class="action-buttons">
            <button @click="addToCart" class="btn">
              添加商品到购物车
            </button>
            <button @click="cartStore.clearCart" class="btn" v-if="cartStore.items.length > 0">
              清空购物车
            </button>
          </div>
        </div>
      </div>

      <CodeBlock :code="userStoreExampleCode"
      </CodeBlock>

      <CodeBlock :code="cartStoreExampleCode"></CodeBlock>
    </section>

    <section class="example-section">
      <h3>2. 组合式 Store 风格</h3>
      
      <div class="demo-box">
        <div class="store-data">
          <h4>主题设置 (Theme Store - 组合式风格)</h4>
          <div class="data-display">
            <p><strong>当前主题:</strong> {{ themeStore.theme }}</p>
            <p><strong>字体大小:</strong> {{ themeStore.fontSize }}px</p>
            <p><strong>暗黑模式:</strong> {{ themeStore.isDarkMode ? '开启' : '关闭' }}</p>
          </div>
          
          <div class="theme-controls">
            <select v-model="themeStore.theme" class="form-control form-control--select">
              <option value="light">浅色</option>
              <option value="dark">深色</option>
              <option value="blue">蓝色</option>
              <option value="green">绿色</option>
            </select>
            
            <input 
              type="range" 
              v-model.number="themeStore.fontSize" 
              min="12" 
              max="24" 
              class="form-control"
            />
            
            <label class="dark-mode-toggle">
              <input 
                type="checkbox" 
                v-model="themeStore.isDarkMode"
                class="form-control form-control--checkbox"
              />
              启用暗黑模式
            </label>
          </div>
        </div>
      </div>

      <CodeBlock :code="storeCompositionExampleCode"></CodeBlock>
    </section>

    <section class="example-section">
      <h3>3. Pinia 插件演示</h3>
      
      <div class="demo-box">
        <p>以下是如何使用Pinia插件的示例：</p>
        
        <div class="plugin-demo">
          <h4>持久化插件</h4>
          <p>购物车数据已经通过插件自动保存到localStorage中</p>
          <button @click="simulatePageReload" class="btn">
            模拟页面刷新
          </button>
        </div>
        
        <div class="plugin-demo">
          <h4>开发调试插件</h4>
          <p>Pinia提供了强大的开发工具集成，可以在Vue DevTools中查看状态变化</p>
        </div>
      </div>

      <CodeBlock :code="pluginExampleCode"></CodeBlock>

      <CodeBlock :code="mainJsExampleCode"></CodeBlock>
    </section>

    <section class="example-section">
      <h3>4. Store 间的通信与组合</h3>
      
      <div class="demo-box">
        <div class="store-data">
          <h4>设置 Store (Settings Store)</h4>
          <div class="data-display">
            <p><strong>语言:</strong> {{ settingsStore.language }}</p>
            <p><strong>通知:</strong> {{ settingsStore.notifications ? '开启' : '关闭' }}</p>
            <p><strong>自动保存:</strong> {{ settingsStore.autoSave ? '开启' : '关闭' }}</p>
          </div>
          
          <div class="settings-controls">
            <select v-model="settingsStore.language" class="form-control form-control--select">
              <option value="en">English</option>
              <option value="zh">中文</option>
              <option value="ja">日本語</option>
            </select>
            
            <label class="settings-toggle">
              <input 
                type="checkbox" 
                v-model="settingsStore.notifications"
                class="form-control form-control--checkbox"
              />
              启用通知
            </label>
            
            <label class="settings-toggle">
              <input 
                type="checkbox" 
                v-model="settingsStore.autoSave"
                class="form-control form-control--checkbox"
              />
              自动保存
            </label>
          </div>
        </div>
        
        <div class="store-combination">
          <h4>Store 组合演示</h4>
          <p>当前用户体验配置:</p>
          <ul class="combination-list">
            <li><strong>用户名:</strong> {{ userStore.user?.name || '未登录' }}</li>
            <li><strong>主题:</strong> {{ themeStore.theme }}</li>
            <li><strong>语言:</strong> {{ settingsStore.language }}</li>
            <li><strong>购物车商品数:</strong> {{ cartStore.totalItems }}</li>
          </ul>
          
          <button @click="applyUserPreferences" class="btn" v-if="userStore.isLoggedIn">
            应用用户偏好设置
          </button>
        </div>
      </div>
    </section>

    <!-- 最佳实践部分 -->
    <section class="best-practices">
      <h3>最佳实践</h3>
      
      <div class="practice-item">
        <h4>✅ 模块化设计</h4>
        <p>按照功能域划分不同的store，保持状态管理的清晰和可维护</p>
      </div>
      
      <div class="practice-item">
        <h4>✅ 选择合适的Store风格</h4>
        <p>根据需求选择Options API风格或组合式API风格的Store定义方式</p>
      </div>
      
      <div class="practice-item">
        <h4>✅ 使用插件增强功能</h4>
        <p>利用Pinia的插件系统实现状态持久化、调试、日志记录等功能</p>
      </div>
      
      <div class="practice-item">
        <h4>✅ 异步操作处理</h4>
        <p>在actions中处理所有异步操作，并使用try/catch捕获错误</p>
      </div>
      
      <div class="practice-item">
        <h4>✅ 类型安全</h4>
        <p>与TypeScript结合使用时，为state、getters和actions提供类型定义</p>
      </div>
    </section>
  </div>
</template>

<script>
// CodeBlock 组件用于显示代码示例
import CodeBlock from '@components/CodeBlock.vue'

// 代码示例常量定义
const userStoreExampleCode = `// user.js - 用户状态管理
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: {
      name: '',
      role: '',
      id: null
    },
    isLoggedIn: false
  }),
  
  getters: {
    isAdmin: (state) => state.user.role === 'admin',
    welcomeMessage: (state) => {
      return state.isLoggedIn 
        ? \`欢迎回来，\${state.user?.name || ''}！\` 
        : '请登录以继续'
    }
  },
  
  actions: {
    login(userData) {
      this.user = { ...userData }
      this.isLoggedIn = true
      // 实际应用中这里会调用API
    },
    logout() {
      this.user = { name: '', role: '', id: null }
      this.isLoggedIn = false
    },
    updateProfile(profileData) {
      this.user = { ...this.user, ...profileData }
    }
  }
})`;

const cartStoreExampleCode = `// cart.js - 购物车状态管理
import { defineStore } from 'pinia'
import { computed } from 'vue'

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: []
  }),
  
  getters: {
    totalItems: (state) => state.items.length,
    totalPrice: (state) => state.items.reduce((total, item) => total + item.price * item.quantity, 0),
    // 使用computed的替代写法
    formattedTotal: (state) => {
      const total = state.items.reduce((total, item) => total + (item?.price || 0) * (item?.quantity || 0), 0)
      return \`$\${total ? total.toFixed(2) : '0.00'}\`
    }
  },
  
  actions: {
    addItem(item) {
      const existingItem = this.items.find(i => i.id === item.id)
      if (existingItem) {
        existingItem.quantity++
      } else {
        this.items.push({ ...item, quantity: 1 })
      }
    },
    removeItem(itemId) {
      this.items = this.items.filter(item => item.id !== itemId)
    },
    clearCart() {
      this.items = []
    }
  }
})`;

const storeCompositionExampleCode = `// 使用组合式API定义store
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useProductStore = defineStore('product', () => {
  // 状态
  const products = ref([])
  const loading = ref(false)
  
  // Getters
  const availableProducts = computed(() => {
    return products.value.filter(product => product.inStock)
  })
  
  const productCount = computed(() => products.value.length)
  
  // Actions
  async function fetchProducts() {
    loading.value = true
    try {
      // 模拟API请求
      // const response = await api.get('/products')
      // products.value = response.data
      
      // 模拟数据
      products.value = [
        { id: 1, name: '产品A', price: 99.99, inStock: true },
        { id: 2, name: '产品B', price: 199.99, inStock: false },
        { id: 3, name: '产品C', price: 299.99, inStock: true }
      ]
    } catch (error) {
      console.error('Failed to fetch products:', error)
    } finally {
      loading.value = false
    }
  }
  
  function updateProductStock(productId, inStock) {
    const product = products.value.find(p => p.id === productId)
    if (product) {
      product.inStock = inStock
    }
  }
  
  return {
    // 暴露的状态
    products,
    loading,
    
    // 暴露的getters
    availableProducts,
    productCount,
    
    // 暴露的actions
    fetchProducts,
    updateProductStock
  }
})`;

const pluginExampleCode = `// pinia-plugin-persistence.js
import { markRaw } from 'vue'

// 自定义持久化插件
const persistencePlugin = {
  install(app, options) {
    return {
      store: {
        // 初始化时从localStorage恢复状态
        $initialize() {
          const savedState = localStorage.getItem(this.$id)
          if (savedState) {
            try {
              const parsedState = JSON.parse(savedState)
              this.$patch(parsedState)
            } catch (error) {
              console.error('Failed to restore state:', error)
            }
          }
        },
        
        // 保存状态到localStorage
        $persist() {
          localStorage.setItem(this.$id, JSON.stringify(this.$state))
        }
      }
    }
  }
}

export default persistencePlugin`;

const mainJsExampleCode = `// 在main.js中使用
import { createApp } from 'vue'
import App from './App.vue'
import pinia from './store/persistence'

const app = createApp(App)

// 使用pinia
app.use(pinia)

app.mount('#app')`;

// 导入现有的store（注意：在实际应用中这些store应该已经定义）import pinia from '@store/persistence'
// 这个导入被注释掉，因为实际使用的是示例代码中的store定义
// import { useUserStore } from '@store/user'
// 这些导入被注释掉，因为实际使用的是示例代码中的store定义
  // import { useCartStore } from '@store/cart'
  // import { useThemeStore } from '@store/theme'
// 这个导入被注释掉，因为实际使用的是示例代码中的store定义
  // import { useSettingsStore } from '@store/settings'

export default {
  name: 'PiniaAdvancedDemo',
  components: {
    CodeBlock
  },
  setup() {
    // 使用store
    const userStore = useUserStore()
    const cartStore = useCartStore()
    const themeStore = useThemeStore()
    const settingsStore = useSettingsStore()
    
    // 模拟产品数据
    const sampleProducts = [
      { name: 'Vue 3 进阶指南', price: 29.99 },
      { name: 'Pinia 状态管理实战', price: 39.99 },
      { name: '前端架构设计', price: 49.99 },
      { name: 'TypeScript 高级编程', price: 59.99 }
    ]
    
    // 方法
    function login() {
      userStore.login({
        id: 1,
        name: '张三',
        role: 'user'
      })
    }
    
    function logout() {
      userStore.logout()
    }
    
    function addToCart() {
      // 随机选择一个产品添加到购物车
      const randomIndex = Math.floor(Math.random() * sampleProducts.length)
      cartStore.addItem(sampleProducts[randomIndex])
    }
    
    function simulatePageReload() {
      // 清除当前购物车
      cartStore.clearCart()
      // 然后从localStorage恢复（模拟页面刷新后的行为）
      setTimeout(() => {
        const savedCart = localStorage.getItem('pinia_cart')
        if (savedCart) {
          try {
            cartStore.$patch(JSON.parse(savedCart))
            alert('购物车数据已从localStorage恢复')
          } catch (error) {
            console.error('恢复购物车失败:', error)
          }
        }
      }, 500)
    }
    
    function applyUserPreferences() {
      // 应用用户偏好设置（演示Store间的协作）
      alert(`已应用用户 ${userStore.user?.name || '未知用户'} 的偏好设置！`)
    }
    
    // 初始化主题
    themeStore.initTheme()
    
    return {
      userStore,
      cartStore,
      themeStore,
      settingsStore,
      login,
      logout,
      addToCart,
      simulatePageReload,
      applyUserPreferences
    }
  }
}
</script>

<style scoped>
/* 定义CSS变量 */
:root {
  --color-primary: #42b883;
  --color-primary-dark: #3aa876;
  --color-secondary: #1890ff;
  --color-secondary-dark: #096dd9;
  --color-text-primary: #333;
  --color-text-secondary: #666;
  --color-text-muted: #999;
  --color-background-light: #f8f9fa;
  --color-background-blue: #f0f8ff;
  --color-background-white: #ffffff;
  --color-border-light: #eaeaea;
  --color-border-default: #ddd;
  --color-white: #ffffff;
  
  --spacing-xs: 5px;
  --spacing-sm: 8px;
  --spacing-md: 10px;
  --spacing-lg: 15px;
  --spacing-xl: 20px;
  --spacing-xxl: 30px;
  --spacing-xxxl: 40px;
  
  --border-radius-sm: 4px;
  --border-radius-md: 6px;
  --border-radius-lg: 8px;
  --border-radius-xl: 12px;
  --border-radius-pill: 50px;
  
  --apple-transition: all 0.25s cubic-bezier(0.25, 0.1, 0.25, 1);
}

/* 主容器样式 */
.demo-container {
  padding: var(--spacing-xl);
  max-width: 1200px;
  margin: 0 auto;
}

/* 标题样式 */
.demo-container h2 {
  color: var(--color-text-primary);
  text-align: center;
  margin-bottom: var(--spacing-xl);
}

.demo-container h3 {
  color: var(--color-primary);
  margin-top: var(--spacing-xl);
  margin-bottom: var(--spacing-xl);
  border-bottom: 1px solid var(--color-border-light);
  padding-bottom: var(--spacing-md);
}

.demo-container h4 {
  color: var(--color-text-primary);
  margin-bottom: var(--spacing-md);
}

/* 描述文本 */
.demo-container .description {
  text-align: center;
  color: var(--color-text-secondary);
  margin-bottom: var(--spacing-xxxl);
  font-size: 16px;
}

/* 特性介绍卡片 */
.demo-container .feature-intro {
  display: flex;
  justify-content: space-between;
  gap: var(--spacing-xl);
  margin-bottom: var(--spacing-xxxl);
}

/* 示例部分 */
.demo-container .example-section {
  background-color: var(--color-background-white);
  border-radius: var(--border-radius-md);
  padding: var(--spacing-lg);
  margin-bottom: var(--spacing-xxl);
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.demo-container .example-section .demo-box {
  background-color: var(--color-background-white);
  border-radius: var(--border-radius-xl);
  padding: var(--spacing-xl);
  margin: var(--spacing-lg) 0;
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-xl);
  transition: var(--apple-transition);
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.demo-container .example-section .demo-box .store-data {
  flex: 1;
  min-width: 300px;
  background-color: var(--color-background-white);
  border-radius: var(--border-radius-xl);
  padding: var(--spacing-lg);
  transition: var(--apple-transition);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.demo-container .example-section .demo-box .plugin-demo {
  flex: 1;
  min-width: 250px;
  background-color: var(--color-background-white);
  border-radius: var(--border-radius-lg);
  padding: var(--spacing-lg);
  margin: var(--spacing-md) 0;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.demo-container .example-section .demo-box .store-combination {
  flex: 1;
  min-width: 300px;
  background-color: var(--color-background-white);
  border-radius: var(--border-radius-lg);
  padding: var(--spacing-lg);
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.demo-container .example-section .demo-box .store-combination .combination-list {
  padding-left: 20px;
}

.demo-container .example-section .demo-box .store-combination .combination-list li {
  margin: var(--spacing-sm) 0;
}

/* 通用按钮样式 */
.demo-container .demo-button {
  background-color: var(--color-primary);
  color: var(--color-white);
  border: 1px solid transparent;
  border-radius: var(--border-radius-sm);
  padding: var(--spacing-sm) var(--spacing-xl);
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.demo-container .demo-button:hover {
  background-color: var(--color-primary-dark);
}

.demo-container .demo-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

/* 购物车相关样式 */
.demo-container .cart-items {
  max-height: 200px;
  overflow-y: auto;
  margin: var(--spacing-lg) 0;
  padding: var(--spacing-md);
  background-color: var(--color-background-light);
  border-radius: var(--border-radius-sm);
}

/* 美化滚动条 */
.demo-container .cart-items {
  scrollbar-width: thin;
  scrollbar-color: var(--color-border-default) transparent;
}

.demo-container .cart-items::-webkit-scrollbar {
  width: 6px;
}

.demo-container .cart-items::-webkit-scrollbar-track {
  background: transparent;
}

.demo-container .cart-items::-webkit-scrollbar-thumb {
  background-color: var(--color-border-default);
  border-radius: 3px;
}

.demo-container .cart-items .cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-sm);
  margin-bottom: var(--spacing-sm);
  background-color: var(--color-background-white);
  border-radius: var(--border-radius-sm);
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.demo-container .cart-items .cart-item .quantity-control {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.demo-container .cart-items .cart-item .quantity-control .quantity-btn {
  width: 24px;
  height: 24px;
  border: none;
  background-color: var(--color-secondary);
  color: white;
  border-radius: var(--border-radius-sm);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  line-height: 1;
}

.demo-container .cart-items .cart-item .quantity-control .quantity-btn:hover {
  background-color: var(--color-secondary-dark);
}

/* 空购物车状态 */
.demo-container .cart-items .empty-cart {
  color: var(--color-text-muted);
  font-style: italic;
  padding: var(--spacing-xl) 0;
  text-align: center;
}

/* 控制组件样式 */
.demo-container .theme-controls,
.demo-container .settings-controls {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
  margin-top: var(--spacing-lg);
}

.demo-container .theme-controls .theme-select,
.demo-container .settings-controls .settings-select {
  width: 100%;
  padding: var(--spacing-sm) var(--spacing-lg);
  border: 1px solid var(--color-border-default);
  border-radius: var(--border-radius-sm);
  font-size: 0.875rem;
  transition: all 0.3s ease;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23666' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 10px center;
  padding-right: 35px;
}

.demo-container .theme-controls .font-size-slider {
  width: 100%;
}

.demo-container .theme-controls .dark-mode-toggle,
.demo-container .settings-controls .settings-toggle {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  cursor: pointer;
}

/* 最佳实践部分 */
.demo-container .best-practices {
  background-color: var(--color-background-blue);
  border-radius: var(--border-radius-lg);
  padding: var(--spacing-xl);
  margin-top: var(--spacing-xxxl);
}

.demo-container .best-practices .practice-item {
  margin-bottom: var(--spacing-lg);
  background-color: var(--color-background-white);
  border-radius: var(--border-radius-md);
  padding: var(--spacing-md);
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.demo-container .best-practices .practice-item h4 {
  margin-top: 0;
  color: var(--color-secondary);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .demo-container .feature-intro {
    flex-direction: column;
  }
  
  .demo-container .example-section .demo-box {
    flex-direction: column;
  }
  
  .demo-container .example-section .demo-box .store-data {
    min-width: 100%;
  }
}
</style>